/*!
 * 数据模型 
 * Copyright(c) purenode
 * @author yangjian102621@gmail.com
 * MIT Licensed
 */

"use strict";

var FAIL = 'FAIL';

/**
 * 构造函数
 */
function model(app, table) {
	this.pk = "id"; //主键
	this.db = app.getDB();
	this.table = table;
}

/**
 * 设置主键
 */
model.prototype.setPK = function(primaryKey) {
	this.pk = primaryKey; 
}	

/**
 * 添加数据
 */
model.prototype.add = function(obj, callback) {
	if ( Object.prototype.toString.apply(obj) != "[object Object]" ) {
		return false;
	}
	//build query string
	var fields = [];
	var values = [];
	for ( var key in obj ) {
		fields.push(key);
		values.push(obj[key]);
	}
	fields = "`"+fields.join("`,`")+"`";
	values = "'"+values.join("','")+"'";
	var query = "INSERT INTO "+this.table+"("+fields+") VALUES ("+values+")"
	this.db.query(query, callback);
}

/**
 * 更新数据
 */
model.prototype.update = function(obj, callback) {
	if ( Object.prototype.toString.apply(obj) != "[object Object]" ) {
		callback(FAIL, null);
		return;
	}
	if ( !obj[this.pk] ) {
		callback(FAIL, null);
	}
	//build query string
	var updateStr = [];
	for ( var key in obj ) {

		if ( key == this.pk ) continue;
		
		updateStr.push("`"+key+"`='"+obj[key]+"'");
	}
	var setStr = updateStr.join(",");
	var query = "UPDATE "+this.table+" SET "+setStr+" WHERE "+this.pk+" = '"+obj[this.pk]+"'";
	this.db.query(query, callback);

} 

/**
 * 批量更新
 */
model.prototype.updates = function(obj, condi, callback) {
	//build query string
	var updateStr = [];
	for ( var key in obj ) {

		if ( key == this.pk ) continue;
		
		updateStr.push("`"+key+"`='"+obj[key]+"'");
	}
	var setStr = updateStr.join(",");
	var query = "UPDATE "+this.table+" SET "+setStr+" WHERE "+condi;
	this.db.query(query, callback);

}

/**
 * 删除数据
 */
model.prototype.delete = function(id, callback) {

	if ( !id ) return false;
	
	var query = "DELETE FROM "+this.table+" WHERE "+this.pk+" = '"+id+"'";
	this.db.query(query, callback);

}

/**
 * 批量删除
 */
model.prototype.deletes = function(condi, callback) {
	var query = "DELETE FROM "+this.table+" WHERE "+condi;
	this.db.query(query, callback);
}

/**
 * 统计数量
 */
model.prototype.count = function(condi, callback) {

	var query = "select count(*) as total FROM "+this.table;
	if ( condi && typeof condi == 'string' ) {
		query += " WHERE "+condi;
	}
	if ( typeof condi == "function" ) {
		callback = condi;
	}
	this.db.query(query, function(err,rows) {
		if ( err == null ) {
			callback(err, rows[0].total);
		} else {
			callback(err, rows);
		}
	});
}

module.exports = {

	//创建模型实例
	getInstance : function(app, table) {
		return new model(app, table);
	} 
}
